package cn.edu.tju.elm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.tju.core.model.Order;
import cn.edu.tju.elm.service.OrderService;
import cn.edu.tju.core.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/t_order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping
    public HttpResult create(@RequestBody Order order) {
        boolean saved = orderService.save(order);
        return saved ? HttpResult.ok(order) : HttpResult.fail("创建失败");
    }

    @PutMapping("/{id}")
    public HttpResult update(@PathVariable Integer id, @RequestBody Order order) {
        order.setId(id);
        boolean updated = orderService.updateById(order);
        return updated ? HttpResult.ok(order) : HttpResult.fail("更新失败");
    }

    @DeleteMapping("/{id}")
    public HttpResult delete(@PathVariable Integer id) {
        boolean removed = orderService.removeById(id);
        return removed ? HttpResult.ok(true) : HttpResult.fail("删除失败");
    }

    @GetMapping("/{id}")
    public HttpResult get(@PathVariable Integer id) {
        Order order = orderService.getById(id);
        return order != null ? HttpResult.ok(order) : HttpResult.fail("不存在");
    }

    @GetMapping("/list")
    public HttpResult list(@RequestParam(required = false) Integer userId,
                       @RequestParam(required = false) Integer status,
                       @RequestParam(defaultValue = "1") long page,
                       @RequestParam(defaultValue = "10") long size) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        if (userId != null) {
            qw.eq("user_id", userId);
        }
        if (status != null) {
            qw.eq("status", status);
        }
        Page<Order> p = orderService.page(new Page<>(page, size), qw);
        return HttpResult.ok(p);
    }

    @GetMapping("/user/{userId}")
    public HttpResult getOrdersByUserId(@PathVariable Integer userId) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        List<Order> orders = orderService.list(qw);
        return HttpResult.ok(orders);
    }
}


